package com.kyd.auth.service;

import com.kyd.api.vo.DriverAccountVO;
import com.kyd.auth.kit.JwtTokenProvider;
import com.kyd.auth.modle.DriverAccount;
import com.kyd.auth.repository.DriverAccountRepository;
import com.kyd.base.exception.KydException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhuangqi
 * @date 2019-03-27
 */
@Service
public class DriverAccountServiceImpl implements DriverAccountService {

    @Autowired
    private DriverAccountRepository accountRepository;

    @Autowired
    private JwtTokenProvider tokenProvider;


    @Override
    public void register(String phone, String password) throws KydException {
        if (accountRepository.existsByPhone(phone)) {
            throw new KydException("账号已存在");
        }
        DriverAccount account = new DriverAccount();
        account.setPhone(phone);
        //TODO 这里暂时没有做明文加密
        account.setPassword(password);
        accountRepository.save(account);
    }

    @Override
    public String login(String phone, String password) throws KydException {
        DriverAccount account = accountRepository.findByPhone(phone);
        if (null == account) {
            throw new KydException("账号不存在");
        }
        if (!account.getPassword().equals(password)) {
            throw new KydException("密码错误");
        }
        //颁发token
        return tokenProvider.generateToken(account.getId());
    }

    @Override
    public boolean verify(String token) {
        return tokenProvider.validateToken(token);
    }

    @Override
    public DriverAccountVO get(Long id) {
        DriverAccountVO result = new DriverAccountVO();
        accountRepository.findById(id).ifPresent(account -> {
            result.setId(account.getId());
            result.setNickname(account.getNickname());
            result.setPhone(account.getPhone());
        });
        return result;
    }
}
